/*
 * MediaFormatJson.cpp
 *
 *  Created on: 2016年6月23日
 *      Author: terry
 */

#include "MediaFormatJson.h"
#include "Base64.h"
#include "TByteBuffer.h"


namespace av
{

MediaFormatJson::MediaFormatJson()
{
}

MediaFormatJson::~MediaFormatJson()
{
}

void MediaFormatJson::toJson(const MediaFormat& fmt, Json::Value& value)
{
    value["duration"] = fmt.m_duration;
    value["codec"] = fmt.m_codec;
    value["width"] = fmt.m_width;
    value["height"] = fmt.m_height;
    value["framerate"] = fmt.m_framerate;
    value["bitrate"] = fmt.m_bitrate;
    value["profile"] = fmt.m_profile;
    value["clockRate"] = fmt.m_clockRate;

    if (fmt.m_videoProp.size() > 0)
    {
        comn::ByteBuffer buffer;
        buffer.resize(fmt.m_videoProp.size());
        comn::Base64::encode((char*)buffer.data(), buffer.capacity(), (const uint8_t*)fmt.m_videoProp.c_str(), fmt.m_videoProp.size());

        value["videoProp"] = buffer.c_str();
    }
    

    value["audioCodec"] = fmt.m_audioCodec;
    value["channels"] = fmt.m_channels;
    value["sampleRate"] = fmt.m_sampleRate;
    value["sampleBits"] = fmt.m_sampleBits;
    value["frameSize"] = fmt.m_frameSize;
    value["audioBitrate"] = fmt.m_audioBitrate;
    value["audioRate"] = fmt.m_audioRate;
}

bool MediaFormatJson::fromJson(MediaFormat& fmt, Json::Value& value)
{
    fmt.m_duration = value["duration"].asInt();
    fmt.m_codec = value["codec"].asInt();
    fmt.m_width = value["width"].asInt();
    fmt.m_height = value["height"].asInt();
    fmt.m_framerate = value["framerate"].asInt();
    fmt.m_bitrate = value["bitrate"].asInt();
    fmt.m_profile = value["profile"].asInt();

    std::string prop = value["videoProp"].asString();
    if (!prop.empty())
    {
        comn::ByteBuffer buffer;
        buffer.resize(prop.size() * 2);
        int length = comn::Base64::decode(buffer.data(), buffer.capacity(), prop.c_str(), prop.size());
        fmt.setVideoProp(buffer.data(), length);
    }

    fmt.m_audioCodec = value["audioCodec"].asInt();
    fmt.m_channels = value["channels"].asInt();
    fmt.m_sampleRate = value["sampleRate"].asInt();
    fmt.m_sampleBits = value["sampleBits"].asInt();
    fmt.m_frameSize = value["frameSize"].asInt();
    fmt.m_audioBitrate = value["audioBitrate"].asInt();
    
    return true;
}

void MediaFormatJson::makeError(Json::Value& value, int err, const char* desc)
{
    value["error"] = err;
    if (desc)
    {
        value["desc"] = desc;
    }
}


} /* namespace av */
